using System;
using sharpsvr.attributes;
using sharpsvr.common;
using sharpsvr.protocol.serializer;

namespace sharpsvr.protocol
{
    public class SerializerManager : Singleton<SerializerManager>
    {

        private volatile System.Collections.Concurrent.ConcurrentDictionary<string, ISerializable>
            serializers = new System.Collections.Concurrent.ConcurrentDictionary<string, ISerializable>();

        public ISerializable GetSerializer(string name)
        {
            ISerializable serializer = null;
            if (serializers.ContainsKey(name))
            {
                serializers.TryGetValue(name, out serializer);
                return serializer;
            }

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    var attributes = type.GetCustomAttributes(typeof(SharpSerializerAttribute), false);
                    if (attributes != null && attributes.Length > 0 &&
                        name.ToLower().Equals((attributes[0] as SharpSerializerAttribute).Name.ToLower()))
                    {
                        serializer = Activator.CreateInstance(type) as ISerializable;
                        serializers[name] = serializer;
                        break;
                    }
                }
            }
            if (serializer == null) serializer = JsonSerializer.GetInstance();
            return serializer;
        }
    }
}